package com.li.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.li.constant.MessageConstant;
import com.li.entity.PageResult;
import com.li.entity.QueryPageBean;
import com.li.entity.Result;
import com.li.service.UserService;
import com.li.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Reference
    UserService userService;
    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    @RequestMapping("/add")
    public Result add(Integer[] roleIds,@RequestBody com.li.pojo.User user){
        //加密密码
        if(user.getPassword()!=null){
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        }
        userService.add(user,roleIds);
        return new Result(true,"新增会员成功");
    }

    @RequestMapping("/findPageByCondition")
    public PageResult findPageByCondition(@RequestBody QueryPageBean queryPageBean){

        PageResult result=userService.findByCondition(queryPageBean);
        return result;
    }

    @RequestMapping("/delete")
    public Result delete(Integer userId){

        userService.delete(userId);

        return new Result(true,"删除用户成功");
    }

    @RequestMapping("/findRoleByUserId")
    public Result findRoleByUserId(Integer userId){

        List<Integer> list=userService.findRoleByUserId(userId);

        return new Result(true,"",list);
    }

    @RequestMapping("/get")
    public Result get(Integer userId){
        com.li.pojo.User user=userService.get(userId);
        return new Result(true,"",user);
    }

    @RequestMapping("/update")
    public Result update(Integer[] roleIds, @RequestBody com.li.pojo.User user){
        //更新
        userService.update(user,roleIds);
        return new Result(true,"更新成功");
    }


}
